package com.whately.core.database.common.recorderoperate;


import com.whately.core.base.event.IRecorderOperate;
import com.whately.core.base.exception.ServiceException;
import com.whately.core.base.model.RecorderModel;
import com.whately.core.database.common.dal.mapper.RecorderOperateMapper;
import com.whately.core.database.common.dal.mapper.RecorderOperateMapperExt;
import com.whately.core.database.common.dal.model.RecorderOperate;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 操作日志记录
 */
@Service
@Slf4j
public class RecorderOperateByDbImpl implements IRecorderOperate{

    @Resource
    RecorderOperateMapper recorderOperateMapper;

    @Resource
    RecorderOperateMapperExt recorderOperateMapperExt;

    @Resource
    private MapperFactory mapperFactory;

    @Override
    public int record(RecorderModel recorderModel) {
        RecorderOperate operate =  mapperFactory.getMapperFacade().map(recorderModel, RecorderOperate.class);
        if(operate.getTyp()==null){
            operate.setTyp(0);
        }
        if(operate.getBizId()==null){
            operate.setBizId(0L);
        }
        if(operate.getCid()==null){
            operate.setCid(0L);
        }
        return recorderOperateMapper.insert(operate);
    }

    @Override
    public int getHandlerCode(){
        return 888;
    }

    @Override
    public int testQuery() throws ServiceException {
        try{
            recorderOperateMapperExt.selectTestConnectionQuery();
        }catch (Exception e){
            //表未建，直接忽略改处理器
            if(e instanceof org.springframework.jdbc.BadSqlGrammarException){
                log.error("Recorder Operate error BadSqlGrammarException 4 recorderOperateMapperExt selectTestConnectionQuery");
                throw new ServiceException(888,"BadSqlGrammarException error happen!");
            }else{
                log.error("Recorder Operate error",e);
                throw new ServiceException(400,"error happen!");
            }
        }
        return 1;
    }
}
